package com.hugh.lagouservicecode.controller;

import com.hugh.lagouservicecode.service.EmailServiceFeignClient;
import com.hugh.lagouservicecode.service.GenerateCodeService;
import com.hugh.lagouservicecode.service.LagouAuthCodeService;
import com.hugh.lagouservicecode.service.impl.entity.LagouAuthCodeEntity;
import com.hugh.lagouservicecode.util.CheckCodeResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * @Author: Hugh
 * @Date: 2020/7/19
 */
@RestController
@RequestMapping("/api/code")
@Slf4j
public class CodeController {


    @Autowired
    private EmailServiceFeignClient emailServiceFeignClient;

    @Autowired
    private GenerateCodeService generateCodeService;

    @Autowired
    private LagouAuthCodeService lagouAuthCodeService;
    /**
     * ⽣成验证码并发送到对应邮箱
     * @param email 邮箱
     * @return 成功true，失败
     * false
     */
    @GetMapping("/create/{email}")
    public Boolean create(@PathVariable String email){
        //发送
        Integer code = generateCodeService.generate();
        emailServiceFeignClient.sendCode(email, code.toString());
        //保存
        //验证码10分钟内有效
        LocalDateTime expiretime = LocalDateTime.now().plusMinutes(10L);
        LagouAuthCodeEntity request = LagouAuthCodeEntity.builder()
                .code(code.toString())
                .email(email)
                .expiretime(expiretime)
                .build();
        log.info("保存的验证码信息是:{}", request.toString());
        lagouAuthCodeService.saveCode(request);
        return Boolean.TRUE;
    }

    /**
     * 校验验证码是否正确，
     * @param email 邮箱
     * @param code token
     * @return 0正确1错误2超时
     */
    @GetMapping("/validate/{email}/{code}")
    public Integer validate(@PathVariable String email, @PathVariable String code){
        CheckCodeResult checkCodeResult = lagouAuthCodeService.checkCode(email, code);
        return checkCodeResult.getValue();
    }

}
